﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Web.UI.HtmlControls;
using System.Data;
using System.IO;
using System.Web.Security;
using System.Linq;
using App.Core.Base.Model;
using App.Core.Extensions;
using App.Core.DB;

/// <summary>
/// Summary description for WebUtil
/// </summary>
public class WebUtil 
{    
    public static String GetPageTitle(string title)
    {
        return string.Format("BTC: {0}", title);
    }
    /// <summary>
    /// Builds Url With the all Query String 
    /// </summary>
    /// <returns></returns>
    public static String BuildUrlWithQueryStrings()
    {
        StringBuilder sb = new StringBuilder(10);
        if (HttpContext.Current.Request.QueryString.Count > 0)
        {
            for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
            {
                if (i == 0)
                    sb.AppendFormat("?{0}={1}", HttpContext.Current.Request.QueryString.GetKey(i), HttpContext.Current.Request.QueryString[i]);
                else
                    sb.AppendFormat("&{0}={1}", HttpContext.Current.Request.QueryString.GetKey(i), HttpContext.Current.Request.QueryString[i]);
            }
        }
        return sb.ToString();
    }
    /// <summary>
    /// Builds Query Strings Excluding Ignore List 
    /// </summary>
    /// <param name="ignoreList"></param>
    /// <returns></returns>
    public static String BuildUrlWithQueryStrings(IList<String> ignoreList)
    {
        StringBuilder sb = new StringBuilder(10);
        if (HttpContext.Current.Request.QueryString.Count > 0)
        {
            bool isFirst = true;
            for (int i = 0; i < HttpContext.Current.Request.QueryString.Count; i++)
            {
                var result = ignoreList.SingleOrDefault(S => S == HttpContext.Current.Request.QueryString.GetKey(i));
                if (result == null)
                {
                    if (isFirst)
                    {
                        sb.AppendFormat("?{0}={1}", HttpContext.Current.Request.QueryString.GetKey(i), HttpContext.Current.Request.QueryString[i]);
                        isFirst = false;
                    }
                    else
                        sb.AppendFormat("&{0}={1}", HttpContext.Current.Request.QueryString.GetKey(i), HttpContext.Current.Request.QueryString[i]);
                }
            }
        }
        return sb.ToString();
    }
    /// <summary>
    /// Encodes text to show in the web page
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static String Encode(String text)
    {
        return HttpContext.Current.Server.HtmlEncode(text);
    }
    /// <summary>
    /// Encodes text and replaces newline to show in web pages
    /// </summary>
    /// <param name="text"></param>
    /// <returns></returns>
    public static String FormatText(String text)
    {
        if (text.IsNullOrEmpty())
            return String.Empty;

        return Encode(text).Replace(Environment.NewLine, "<br />").Replace("\n", "<br />");
    }
    /// <summary>
    /// Builds a DateTime Object from a BD Format Date. (24/10/2009)
    /// </summary>
    /// <param name="date"></param>
    /// <returns></returns>
    public static DateTime GetDate(String date)
    {
        if (!date.IsNullOrEmpty())
        {           
            return DateTime.ParseExact(date, ConfigReader.CSharpCalendarDateFormat, null);            
        }
        return DateTime.MinValue.SqlDateTimeMinValue();
    }
    /// <summary>
    /// Checks Whether an Uploaded file is a Valid Image File Or Not
    /// </summary>
    /// <param name="httpPostedFile"></param>
    /// <returns></returns>
    public static bool IsValidImageFile(HttpPostedFile httpPostedFile)
    {
        if (httpPostedFile.ContentLength > 0)
        {
            string extension = Path.GetExtension(httpPostedFile.FileName);
            return IsValidImageFileExtension(extension);
        }
        return false;
    }
    /// <summary>
    /// Checks for a valid file extension for an image.
    /// </summary>
    /// <param name="extension"></param>
    /// <returns></returns>
    private static bool IsValidImageFileExtension(string extension)
    {
        if (String.Compare(extension, ".jpg", true) == 0)
            return true;
        else if (String.Compare(extension, ".jpeg", true) == 0)
            return true;
        else if (String.Compare(extension, ".gif", true) == 0)
            return true;
        else if (String.Compare(extension, ".png", true) == 0)
            return true;
        return false;
    }
    /// <summary>
    /// Prepares a DIV box to show as a message box in the UI
    /// </summary>
    /// <param name="divMessage"></param>
    /// <param name="message"></param>
    /// <param name="isErrorMessage"></param>
    public static void ShowMessageBox(HtmlGenericControl divMessage, string message, bool isErrorMessage)
    {
        divMessage.InnerHtml = message;
        divMessage.Attributes["class"] = isErrorMessage ? AppConstants.UI.ERROR_MESSAGE_BOX_CLASS : AppConstants.UI.MESSAGE_BOX_CLASS;
        divMessage.Visible = true;
    }
    /// <summary>
    /// Reads HTML Template from File System
    /// </summary>
    /// <param name="templateFileName"></param>
    /// <returns></returns>
    public static String ReadEmailTemplate(String templateFileName)
    {
        String filePath = HttpContext.Current.Server.MapPath("/EmailTemplates");
        filePath = Path.Combine(filePath, templateFileName);
        return File.ReadAllText(filePath);
    }
    /// <summary>
    /// Gets Currently Hosted Domain Address
    /// </summary>
    /// <returns></returns>
    public static String GetDomainAddress()
    {
        return String.Format("http://{0}/", HttpContext.Current.Request.Url.Host);
    }

    public static String GetContentDetailsUrl(int contentId)
    {
        return String.Format("{0}?{1}={2}", AppConstants.Pages.SHOW_CONTENT, AppConstants.QueryString.ID, contentId);
    }
    /// <summary>
    /// Gets Completed External Absolute URL
    /// </summary>
    /// <param name="url"></param>
    /// <returns></returns>
    public static string GetCompleteUrl(String url)
    {
        return url.ToLower().StartsWith("http://") ? url : String.Format("http://{0}", url);
    }
    /// <summary>
    /// Gets the IP Address of the Requested Client
    /// </summary>
    /// <returns></returns>
    public static string GetRemoteIPAddress()
    {
        return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
    }
    /// <summary>
    /// Signouts the user.
    /// </summary>
    public static void SignoutUser()
    {
        SessionCache.ClearSession();
        FormsAuthentication.SignOut();
        HttpContext.Current.Response.Redirect(FormsAuthentication.LoginUrl);
    }

    /// <summary>
    /// Gets the request param value in long.
    /// </summary>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static int GetQueryStringInInt(string key)
    {
        int paramValue = 0;
        int.TryParse(HttpContext.Current.Request[key], out paramValue);

        return paramValue;
    }

    /// <summary>
    /// Gets the request param value in byte.
    /// </summary>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static byte GetQueryStringInByte(string key)
    {
        byte paramValue = 0;
        byte.TryParse(HttpContext.Current.Request[key], out paramValue);

        return paramValue;
    }
    
    /// <summary>
    /// Gets the request param value in string.
    /// </summary>
    /// <param name="key">The key.</param>
    /// <returns></returns>
    public static string GetQueryStringInString(string key)
    {
        string paramValue = HttpContext.Current.Request[key];
        return paramValue;
    }
    public static string GetQueryStringValue(Uri uri, String key)
    {
        String queryString = uri.Query;
        if (!queryString.IsNullOrEmpty())
        {
            queryString = queryString.Replace("?", String.Empty);
            String[] pairs = queryString.Split('&');
            if (pairs.Length > 0)
            {
                foreach (String str in pairs)
                {
                    if (str.StartsWith(key))
                    {
                        String[] parts = str.Split('=');
                        if (parts.Length > 1)
                            return parts[1];
                    }
                }
            }
        }
        return String.Empty;
    }
    /// <summary>
    /// Logins the user.
    /// </summary>
    public static void LoginUser()
    {
        if (HttpContext.Current.User.Identity.IsAuthenticated && SessionCache.CurrentUser == null)
        {
            String userName = HttpContext.Current.User.Identity.Name;

            App.Data.BtcHousingEntities context = new App.Data.BtcHousingEntities();
            App.Data.User user = context.Users.FirstOrDefault(U => string.Compare(U.LoginName, userName, true) == 0);
            if (user != null)
            {
                ///Load Group and Group Permissions                                
                //user.UserGroup = groupDAO.Get(user.GroupCode);                
                SessionCache.CurrentUser = user;
            }
        }
    }    
    /// <summary>
    /// Binds a Dropdownlist Controls to a Collection
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="ddl"></param>
    /// <param name="entities"></param>
    /// <param name="displayField"></param>
    /// <param name="valueField"></param>
    public static void BindListBox<T>(ListBox lst, IList<T> entities, String displayField, String valueField)
        where T : BaseEntity
    {
        if (entities == null || entities.Count == 0)
        {
            if (lst.Items.Count > 0)
                lst.Items.Clear();
            lst.DataSource = null;
        }
        else
        {
            lst.DataSource = entities;
            lst.DataTextField = displayField;
            lst.DataValueField = valueField;
        }
        lst.DataBind();
    }
    /// <summary>
    /// Adds Client Side Confirmation Text to a Server Side Button Control according to the Validation Group
    /// </summary>
    /// <param name="btn"></param>
    /// <param name="message"></param>
    /// <param name="isSaveButton"></param>
    public static void AddCorfirmation(Button btn, String message, bool isSaveButton)
    {
        if (isSaveButton)
        {
            if (!btn.ValidationGroup.IsNullOrEmpty())
                btn.Attributes.Add("ValidationGroupName", btn.ValidationGroup);

            btn.Attributes["onclick"] = "return ShowSaveConfirmation(this);";
            btn.Attributes.Add(AppConstants.CONFIRMATION_MSG_CUSTOM_ATTR, message);            
        }
        else
            btn.Attributes["onclick"] = String.Format("return confirm('{0}');", message);
    }
    
    public static String GetDeleteConfirmation()
    {
        return String.Format("onclick=\"return confirm('Sure to Delete?')\"");
    }

    public static String GetEditPermissionDeniedMessage()
    {
        return String.Format("javascript:alert('{0}');javascript:void(0);", AppConstants.Message.EDIT_PERMISSION_DENIED);
    }
    public static String GetDeleteLink(String url, String deleteMessage)
    {
        deleteMessage = deleteMessage.IsNullOrEmpty() ? "Sure to Delete Data?" : deleteMessage;
        return String.Format("javascript: ConfirmDelete('{0}', '{1}'); void(0);", url, deleteMessage);
    }
    public static String GetDeletePermissionDeniedMessage()
    {
        return String.Format("javascript:DeleteDenied('{0}');javascript:void(0);", AppConstants.Message.DELETE_PERMISSION_DENIED);
    }
    
    /// <summary>
    /// Determines Whether a Server Control Caused Post Back Or Not
    /// </summary>
    /// <param name="uniqueID">Unique ID of the Server Control</param>
    /// <param name="isListControls">Whether this is listing control like RadioButtonList</param>
    /// <returns></returns>
    public static bool IsPostBackBy(String uniqueID, bool isListControl)
    {
        HttpRequest Request = HttpContext.Current.Request;
        if(isListControl)
            return Request.Params.Get("__EVENTTARGET").Contains(uniqueID);
        else
            return (!(Request.Form[uniqueID] == null)) || (!(Request.Form["__EVENTTARGET"] == null) && Request.Form["__EVENTTARGET"].Equals(uniqueID)) || ((!(Request.Form[uniqueID + ".x"] == null)) && (!(Request.Form[uniqueID + ".y"] == null)));
    }
    
    //public static bool IsAdminUser()
    //{
    //    if (SessionCache.CurrentUser != null)
    //    {
    //        if (String.Compare(SessionCache.CurrentUser.UserID, "Admin", true) == 0)
    //            return true;
    //    }
    //    return false;
    //}
    /// <summary>
    /// Writes an Excel file from the Exported Data into the Response Stream as a Downloadable File
    /// </summary>
    /// <param name="filePath"></param>
    /// <param name="outputFileName"></param>
    public static void WriteExportedExcel(String filePath, String outputFileName)
    {
        HttpResponse response = HttpContext.Current.Response;
        if (!filePath.IsNullOrEmpty() && File.Exists(filePath))
        {
            byte[] bytes = File.ReadAllBytes(filePath);
            if (bytes != null && bytes.Length > 0)
            {
                response.Buffer = true;
                response.Cache.SetCacheability(HttpCacheability.NoCache);
                response.ContentType = "application/vnd.xls";
                response.AddHeader("content-disposition", String.Format("attachment;filename={0}", outputFileName));
                response.BinaryWrite(bytes);
            }
            File.Delete(filePath);
        }
        response.Flush();
        response.End();
    }

    /// <summary>
    /// Determines whether the current request is from a Mobile Device
    /// </summary>
    /// <returns></returns>
    public static bool IsMobileRequest()
    {
        HttpRequest request = HttpContext.Current.Request;
        if (request.Browser["IsMobileDevice"] == "true" || request.UserAgent.ToUpper().Contains("MIDP") || request.UserAgent.ToUpper().Contains("CLDC"))
            return true;

        return false;
    }
    /// <summary>
    /// Returns Formatted Data Returned from a Data Reader or a Data Table Cell
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    public static String FormatData(object data)
    {
        if (data.GetType() == typeof(String))
            return WebUtil.FormatText(NullHandler.GetString(data));
        else if (data.GetType() == typeof(DateTime))
            return NullHandler.GetDateTime(data).ToString(AppConstants.ValueOf.DATE_FROMAT_DISPLAY);
        else if (data.GetType() == typeof(decimal))
            return String.Format(AppConstants.ValueOf.DECIMAL_FORMAT, NullHandler.GetDecimal(data));
        else if (data.GetType() == typeof(bool))
            return NullHandler.GetBoolean(data) ? "Yes" : "No";
        else
            return NullHandler.GetString(data);
    }
    public static String FormatForTextBox(object data)
    {
        if (data.GetType() == typeof(decimal))
            return String.Format(AppConstants.ValueOf.DECIMAL_FORMAT_FOR_TEXTBOX, NullHandler.GetDecimal(data));
        else
            return NullHandler.GetString(data);
    }
    public static Control FindControlRecursive(Control parentControl, String Id)
    {
        if (parentControl.ID == Id)
            return parentControl;

        foreach (Control Ctl in parentControl.Controls)
        {
            Control FoundCtl = FindControlRecursive(Ctl, Id);
            if (FoundCtl != null)
                return FoundCtl;
        }
        return null;
    }
    public static String GetFormattedFileName(String fileName)
    {
        if (!fileName.IsNullOrEmpty())
        {
            if (fileName.IndexOf('_') > -1)
            {
                String[] nameParts = fileName.Split('_');
                StringBuilder sb = new StringBuilder(10);
                for (int i = 0; i < nameParts.Length; i++)
                {
                    if (i > 0)
                        sb.Append(nameParts[i]);
                }
                return sb.ToString();
            }
            return fileName;
        }
        return String.Empty;
    }
}
